package com.zane.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;

import java.util.Arrays;

@Slf4j
@Configuration
public class SecurityConfig {
    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }
    // 创建过滤器链
    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception{
        log.info("自定义创建安全过滤器链...");
        http
                .csrf(csrf->csrf.disable())
                // ========CORS跨域配置===================
                .cors(cors->cors.configurationSource(corsConfigurationSource()))
                // ============请求授权配置================
                .authorizeHttpRequests(authz->authz
                                .requestMatchers("/api/**").permitAll()
                                .requestMatchers("/admin/**").hasRole("ADMIN")
                                // 认证接口公开
                                .requestMatchers("/auth/login").permitAll()
                                .requestMatchers("/auth/register").permitAll()

                                .requestMatchers("/auth/menu").authenticated()
//                        .requestMatchers("/system/menu/getAllMenuTree").hasRole("ADMIN")
                                // FIXME 允许所有用户访问系统接口
//                        .requestMatchers("/system/").permitAll()
                                .anyRequest().authenticated()
                )
                // 添加自定义的JWT过滤器，在UsernamePasswordAuthenticationFilter之前
                // .addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
        ;
        return http.build();
    }

    // 创建CORS跨域配置源
    @Bean
    public CorsConfigurationSource corsConfigurationSource(){
        CorsConfiguration configuration = new CorsConfiguration();
        // 允许所有域名访问
        configuration.setAllowedOrigins(Arrays.asList("*"));
        // 允许所有请求头
        configuration.setAllowedHeaders(Arrays.asList("*"));
        // 允许所有方法
        configuration.setAllowedMethods(Arrays.asList("PUT", "POST", "GET", "DELETE", "PATCH"));
        // 允许发送cookie
        configuration.setAllowCredentials(true);
        // 缓存时间
        configuration.setMaxAge(3600L);
        // 创建配置源（基于URL路径）
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        // 添加配置应用到所有路径
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration config) throws Exception{
        return config.getAuthenticationManager();
    }
}
